package com.tiger.system.service.impl;

import java.util.List;

import com.tiger.common.exception.ServiceException;
import com.tiger.common.core.domain.entity.Department;
import com.tiger.common.core.domain.entity.SysPost;
import com.tiger.system.mapper.DepartmentMapper;
import com.tiger.system.mapper.SysPostMapper;
import com.tiger.system.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 部门Service业务层处理
 *
 * @author standard
 * @date 2022-10-31
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private SysPostMapper sysPostMapper;

    /**
     * 查询部门
     *
     * @param id 部门主键
     * @return 部门
     */
    @Override
    public Department selectDepartmentById(Long id) {
        return departmentMapper.selectDepartmentById(id);
    }

    /**
     * 查询部门列表
     *
     * @param department 部门
     * @return 部门
     */
    @Override
    public List<Department> selectDepartmentList(Department department) {
        List<Department> departmentList = departmentMapper.selectDepartmentList(department);
        //部门下面挂岗位
        for (Department d : departmentList){
            SysPost sysPost = new SysPost();
            sysPost.setDepartmentId(d.getId());
            List<SysPost> postList = sysPostMapper.selectPostList(sysPost);
            d.getSysPostList().addAll(postList);
        }
        return departmentList;
    }

    /**
     * 新增部门
     *
     * @param department 部门
     * @return 结果
     */
    @Override
    public int insertDepartment(Department department) {
        return departmentMapper.insertDepartment(department);
    }

    /**
     * 修改部门
     *
     * @param department 部门
     * @return 结果
     */
    @Override
    public int updateDepartment(Department department) {
        return departmentMapper.updateDepartment(department);
    }

    /**
     * 批量删除部门
     *
     * @param ids 需要删除的部门主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByIds(Long[] ids) {
        for (Long id : ids) {
            Department department = selectDepartmentById(id);
            //被关联的部门无法被删除
            if (departmentMapper.countDepartment(id) > 0){
                throw new ServiceException(String.format("%1$s已关联岗位,不能删除",department.getDepartmentName()));
            }
        }
        return departmentMapper.deleteDepartmentByIds(ids);
    }

    /**
     * 删除部门信息
     *
     * @param id 部门主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentById(Long id) {
        Department department = selectDepartmentById(id);
        //被关联的部门无法被删除
        if (departmentMapper.countDepartment(id) > 0){
            throw new ServiceException(String.format("%1$s已关联岗位,不能删除",department.getDepartmentName()));
        }
        return departmentMapper.deleteDepartmentById(id);
    }
}
